package com.ifcar.app.weibo;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import net.oauth.OAuth;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthException;
import net.oauth.OAuthProblemException;
import net.oauth.OAuthServiceProvider;
import net.oauth.client.OAuthClient;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.util.EntityUtils;


public class YdNoteLoginHelper {
	private static boolean test = false;
	// 测试环境
	public static final String YD_NOTE_TEST_BASEURL = "http://sandbox.note.corp.youdao.com/";
	// 上线环境
	public static final String YD_NOTE_BASEURL = "http://note.youdao.com/";
	
	public static final String OAUTH_PREFIX = "oauth/";
	public static final String API_PREFIX = "yws/";
	
	public static final String REQUESTTOKENURL = "request_token";
	public static final String AUTHORIZEURL = "authorize";
	public static final String ACCESSTOKENURL = "access_token";

	public static final String allNotebookurl = API_PREFIX + "open/notebook/all.json";
	public static final String createNoteurl = API_PREFIX + "open/note/create.json";
	public static final String YDNOTE_DEFAULT_NOTEBOOK_PAHT = "ydnote_default_notebook_path";

	public static final String AUTHPARAMTERTYLE = "parameterStyle";
	public static final String AUTHPARAMTERTYLEVALUE = "AUTHORIZATION_HEADER";
	
    public static String ydnoteConsumerKey = "7d53ca1f67a2182406fafcb69539c8bf";
    public static String ydnoteConsumerSecret = "0747ea306b9eabcd3033214b8f65ce32";

    private final DefaultHttpClient client;
    private final OAuthAccessor mAccessor;
    
    public YdNoteLoginHelper(){
    	 client = new DefaultHttpClient();
         DefaultHttpRequestRetryHandler retryhandler = new DefaultHttpRequestRetryHandler(0, false);
         client.setHttpRequestRetryHandler(retryhandler);
         
         mAccessor = createOAuthAccessor();
    }
    
	public Map<String, String> requestToken(){
		
		Map<String, String> map = null;
		try {
			
			Map<String, String> paramProps = new HashMap<String, String>();
			map = sendRequest(mAccessor, paramProps, mAccessor.consumer.serviceProvider.requestTokenURL);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return map;
	}
	
	public Map<String, String> requestVerifier(String reqeustToken, String reqeustsecret, String verifier) throws IOException, URISyntaxException, OAuthException{
		
		Map<String, String> paramProps = new HashMap<String, String>();
        paramProps.put(OAuth.OAUTH_TOKEN, reqeustToken);
        paramProps.put(OAuth.OAUTH_VERIFIER, verifier);
        
        mAccessor.tokenSecret = reqeustsecret;
       
        
        Map<String, String> p = sendRequest(mAccessor, paramProps,
        		mAccessor.consumer.serviceProvider.accessTokenURL);
        
		return p;
	}
	
	private Map<String, String> sendRequest(OAuthAccessor accessor, Map<String, String> pro,
	        String url) throws IOException, URISyntaxException, OAuthException {
		
		Header[] headers = OAuthHelper.perpareHeader(accessor, "GET", pro, url);
		
		HttpResponse response = OAuthHelper.requestGet(client, url, headers);
		int code = response.getStatusLine().getStatusCode();

		if (code != HttpStatus.SC_OK) {
		    throw new OAuthProblemException(EntityUtils.toString(
		            response.getEntity()));
		}
		
		String responseString = EntityUtils.toString(response.getEntity(), "utf-8");
		Map<String, String> map = OAuthHelper.processResponse(responseString);
		
	    return map;
	}
	
	/**
	 * 获取BaseUrl
	 * @return
	 */
	public static String getBaseUrl(){
		if(test){// 测试
			return YD_NOTE_TEST_BASEURL;
		}else{// 线上
			return YD_NOTE_BASEURL;
		}
	}
	
	public String authorizeToken(Map<String, String> map) {
		// TODO Auto-generated method stub
		
		String authorizUrl = "";
		try {
			mAccessor.accessToken = map.get("oauth_token");
			mAccessor.tokenSecret = map.get("oauth_token_secret");
			
			Map<String, String> proMap = new HashMap<String, String>();
			proMap.put("oauth_token", map.get(OAuth.OAUTH_TOKEN));
			
			String tempUrl = OAuthHelper.generateQueryString(mAccessor.consumer.serviceProvider.userAuthorizationURL, proMap);
			HttpResponse response = OAuthHelper.requestGet(client, tempUrl);
			
			int code = response.getStatusLine().getStatusCode();
	        if (code == HttpStatus.SC_MOVED_TEMPORARILY) {
	            Header header = response.getFirstHeader("location");
	            proMap.put("orefer", "youdao.com");
	            authorizUrl = OAuthHelper.generateQueryString(header.getValue(),
	            		proMap);
	        }
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return authorizUrl;
	}
	
	private OAuthAccessor createOAuthAccessor() {
		// TODO Auto-generated method stub
        String callbackUrl = null;
        
        String reqUrl = getBaseUrl() + OAUTH_PREFIX + REQUESTTOKENURL;
        String authzUrl = getBaseUrl() + OAUTH_PREFIX + AUTHORIZEURL;
        String accessUrl = getBaseUrl() + OAUTH_PREFIX + ACCESSTOKENURL;
        
        String style = AUTHPARAMTERTYLEVALUE;
        
        OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl,
                authzUrl, accessUrl);
        
        OAuthConsumer consumer = new OAuthConsumer(callbackUrl, ydnoteConsumerKey,
        		ydnoteConsumerSecret, provider);
        
        consumer.setProperty(OAuthClient.PARAMETER_STYLE, style);
        OAuthAccessor accessor = new OAuthAccessor(consumer);
        
        return accessor;
	}
	
	public OAuthAccessor getOAuthAccess(){
		return mAccessor;
	}
	
	public DefaultHttpClient getHttpClient(){
		return client;
	}
	
}
